import os
from .base import BaseClient
from core.tools.get_datetime import GetDateTime
from core.tools.func_utils import FuncUtils
from finance_c2c.local_settings import ONLINE, ZXAppId, ZXAppKey, ZxPublicKey, ZxPrivateKey, ZXoriginMerId, ZXPayCode, \
    ZxPfx, ZxPfxPassword
from core.tools.encryption import hashlib_md5
from core.tools.custom_requests import CustomRequests

funcUtils = FuncUtils()


class ZXClient(BaseClient):
    def __init__(self):
        self.originMerId = ZXoriginMerId
        self.payCode = ZXPayCode
        self.private_key = ZxPrivateKey
        self.public_key = ZxPublicKey  # 公钥
        base_dir = os.path.dirname(os.path.abspath(__file__))
        self.ZxPfx = os.path.join(base_dir, ZxPfx).replace("\\", "/")
        self.ZxPfxPassword = ZxPfxPassword

    def create_order(self, frontEndUrl, cashAmount, originSerialNo, goodsInf=None):
        params = {
            "msgHeader": self.get_msg_header(),
            "msgBody": {
                "originMerId": self.originMerId,  # 商户号
                "originTranTime": GetDateTime.format_datetime("%Y-%m-%d %H:%M:%S"),  # 商户交易时间
                "payCode": self.payCode,  # 支付路由编码：银行分配的支付路由 编码
                "originSerialNo": originSerialNo,  # 商户生成的订单号
                "goodsAmount": 1,  # 商品数量
                "frontEndUrl": frontEndUrl,  # 前端地址
                "cashAmount": cashAmount,
            },
        }
        if goodsInf:
            params["msgBody"]["goodsInf"] = goodsInf
        if ONLINE:
            url = "https://payment.creditcard.citicbank.com/Payment/CiticPay/api/saveMerPayOrder"
            params["msgBody"]["notifyUrl"] = "https://c2c.kalaibao.com/citic/notify"
        else:
            url = "https://e.test.bank.ecitic.com/Payment/CiticPay/api/saveMerPayOrder"
            params["msgBody"]["notifyUrl"] = "http://c2c-uat.kalaibao.com/citic/notify"
        sign = self.get_sign(params.get("msgBody"))
        params["msgSignature"] = sign
        print(params, "请求报文")
        response = self.post(url, json=params, pkcs12_filename=self.ZxPfx, pkcs12_password=self.ZxPfxPassword)
        print(response, "返回数据")
        return params, response

    def search_order(self, originSerialNo, originTranTime):
        """
        :param originSerialNo: 原订单号
        :param originTranTime: 原订单下单时间 originTranTime.format_datetime("%Y-%m-%d %H:%M:%S")
        :return:
        """
        if ONLINE:
            url = "https://payment.creditcard.citicbank.com/Payment/CiticPay/api/query"
        else:
            url = "https://e.test.bank.ecitic.com/Payment/CiticPay/api/query"
        params = {
            "msgHeader": self.get_msg_header(),
            "msgBody": {
                "originMerId": self.originMerId,  # 商户号
                "payCode": self.payCode,  # 支付路由编码：银行分配的支付路由 编码
                "originSerialNo": originSerialNo,  # 原订单号
                "originTranTime": originTranTime,
            },
        }
        sign = self.get_sign(params.get("msgBody"))
        params["msgSignature"] = sign
        print(params, "search_order 请求报文")
        response = self.post(url, json=params, pkcs12_filename=self.ZxPfx, pkcs12_password=self.ZxPfxPassword)
        print(response, "search_order 返回报文")
        return params, response

    def refund_order(self, oldOriginSerialNo, oldOriginTranTime, cashAmount, installment):
        if ONLINE:
            url = "https://payment.creditcard.citicbank.com/Payment/CiticPay/api/return"
        else:
            url = "https://e.test.bank.ecitic.com/Payment/CiticPay/api/return"
        params = {
            "msgHeader": self.get_msg_header(),
            "msgBody": {
                "selFunction": "002",
                "originMerId": self.originMerId,  # 商户号
                "originSerialNo": funcUtils.unique_value,  # 商户退款订单号
                "originTranTime": GetDateTime.format_datetime("%Y-%m-%d %H:%M:%S"),  # 商户退款时间,
                "payCode": self.payCode,  # 支付路由编码：银行分配的支付路由 编码
                "oldOriginSerialNo": oldOriginSerialNo,  # 原支付上送订单号
                "oldOriginTranTime": oldOriginTranTime,  # 原支付上送时间
                "cashAmount": cashAmount,  # 退款金额
                "installment": installment,  # 分期数
            },
        }
        sign = self.get_sign(params.get("msgBody"))
        params["msgSignature"] = sign
        print(params, "中信退款请求参数")
        response = self.post(url, json=params, pkcs12_filename=self.ZxPfx, pkcs12_password=self.ZxPfxPassword)
        print(response, "中信退款返回参数")
        return params, response

    def download_order(self, fileDate):
        """
        :param fileDate:
        :return:
        """
        if ONLINE:
            url = "https://payment.creditcard.citicbank.com/Payment/CiticPay/api/download"
        else:
            url = "http://e.test.bank.ecitic.com/Payment/CiticPay/api/download"
        params = {
            "msgHeader": self.get_msg_header(),
            "msgBody": {
                "originMerId": self.originMerId,  # 商户号
                "originTranTime": GetDateTime.format_datetime("%Y-%m-%d %H:%M:%S"),  # 商户交易时间
                "fileDate": fileDate
            },
        }
        sign = self.get_sign(params.get("msgBody"))
        params["msgSignature"] = sign
        response = self.post(url, json=params, pkcs12_filename=self.ZxPfx, pkcs12_password=self.ZxPfxPassword)
        return params, response


class Oauth(CustomRequests):
    def __init__(self, appid, appkey):
        self.appkey = appkey
        self.appid = appid

    def get_token(self, code):
        if ONLINE:
            url = "https://uc.creditcard.ecitic.com/citiccard/newucwap/oauth/getAccessToken.do"
        else:
            url = "https://e.test.bank.ecitic.com/citiccard/newucwap/oauth/getAccessToken.do"
        secret = hashlib_md5(self.appid + code + self.appkey).upper()
        params = {
            "secret": secret,
            "appid": self.appid,
            "accessCode": code
        }
        print(params)
        response = self.get(url, params=params)
        print(response, "中信 token")
        return response

    def get_openid(self, accessToken):
        if ONLINE:
            url = "https://uc.creditcard.ecitic.com/citiccard/newucwap/oauth/getOpenId.do"
        else:
            url = "https://e.test.bank.ecitic.com/citiccard/newucwap/oauth/getOpenId.do"
        secret = hashlib_md5(self.appid + accessToken + self.appkey).upper()
        params = {
            "secret": secret,
            "appid": self.appid,
            "accessToken": accessToken
        }
        print(params)
        response = self.get(url, params=params)
        print(response, "中信 get_openid response")
        return response


zx_auth = Oauth(ZXAppId, ZXAppKey)
